package com.youdianstar.app.common.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.widget.AppCompatTextView;



/**
 * File: JustifyTextView
 * Author: 82149 Create: 2020/10/20 11:24
 * Changes (from 2020/10/20)
 * --------------------------------------------------
 * describe: 中英文 换行
 * ---------------------------------------------------
 */
public class JustifyTextView extends AppCompatTextView {
    private List<String> mLineTexts;
    private Paint mPaint;

    public JustifyTextView(Context context) {
        this(context, null);
    }

    public JustifyTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public JustifyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mLineTexts = new ArrayList<>();
        mPaint = getPaint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        calculateLines(width);
        int height = (int) (mPaint.getFontSpacing() * mLineTexts.size()) + getPaddingTop() + getPaddingBottom();
        setMeasuredDimension(width, height);
    }

    private void calculateLines(int width) {
        mLineTexts.clear();
        String text = getText().toString();
        if (TextUtils.isEmpty(text)) {
            return;
        }
        int availableWidth = width - getPaddingLeft() - getPaddingRight();
        int start = 0;
        while (start < text.length()) {
            int end = start + 1;
            while (end <= text.length()) {
                String currentLine = text.substring(start, end);
                float lineWidth = mPaint.measureText(currentLine);
                if (lineWidth > availableWidth) {
                    if (end == start + 1) {
                        // 若当前字符就超出宽度，强制添加
                        end++;
                    }
                    break;
                }
                end++;
            }
            mLineTexts.add(text.substring(start, end - 1));
            start = end - 1;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mLineTexts.isEmpty()) {
            super.onDraw(canvas);
            return;
        }
        float y = getPaddingTop() + mPaint.getTextSize();
        for (String line : mLineTexts) {
            canvas.drawText(line, getPaddingLeft(), y, mPaint);
            y += mPaint.getFontSpacing();
        }
    }
}
